ugly number

Ugly number

ugly number

Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
Note that 1 is typically treated as an ugly number.
solve
判断一个数是否是丑数的方法,一个数是丑数,那么它一定满足
$$ num = 2^m3^n5^k (m>=0, n>= 0, k>= 0)$$

1
2
3
4
5
6
7
8
9
bool isUgly(int num) {
if(num <= 0) return false;

while(num%2 == 0) num /= 2;
while(num%3 == 0) num /= 3;
while(num%5 == 0) num /= 5;

return num == 1;
}

ugly number II

Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note that 1 is typically treated as an ugly number.
Hint:

  • The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
  • An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
  • The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
  • Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 2, L2 3, L3 * 5).

solve the problem

题目大意,找到第n个丑数
我们知道一个丑数可以被写成
$$ num = 2^m3^n5^k (m>=0, n>= 0, k>= 0)$$
根据提示:知道第k个丑数,是$U_k$,那么

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
int nthUglyNumber(int n) {
if( n <= 0) return 0;

int *list = (int *)malloc(sizeof(int) * n);
if(list == NULL)
printf("malloc failed\n");

*list = 1; //第一个丑数是1

int iter2 = 0;
int iter3 = 0;
int iter5 = 0;

int i, temp;

for(i = 1; i < n; ++i){
temp = threeMin(*(list+iter2) * 2, *(list +iter3) *3, *(list+iter5) *5);

if(temp == *(list+iter2) *2)
iter2++;
if(temp == *(list + iter3) * 3)
iter3++;
if(temp == *(list + iter5) * 5)
iter5++;

*(list + i) = temp;
}

temp = *(list+n-1);
free(list);
return temp;
}

//找出三个数中的最小的数
int threeMin(int num1, int num2, int num3){
int temp;

temp = (num1 < num2)?num1:num2;
temp = (temp < num3)?temp:num3;

return temp;
}